package com.network.proxy;

import com.network.MyHttpClient;
import com.network.proxy.converter.Converter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by kkmike999 on 2016/06/05.
 *
 * 真正网络请求+解析
 */
public class HttpCall<T> {

	MyHttpClient  client;
	Converter     converter;
	ServiceMethod serviceMethod;
	Object[]      args;

	public HttpCall(ServiceMethod serviceMethod, Converter converter, Object[] args) {
		this.client = new MyHttpClient();

		this.converter = converter;
		this.serviceMethod = serviceMethod;
		this.args = args;
	}

	public T request() {
		try {
			// 参数count与注释count不一致, 抛错
			int argumentCount = args != null ? args.length : 0;
			if (argumentCount != serviceMethod.argumentTypes.length) {
				throw new IllegalArgumentException("Argument count (" + argumentCount + ") doesn't match expected count (" + serviceMethod.argumentTypes.length + ")");
			}

			// 参数
			Map<String, Object> params = new HashMap<>();

			for (int p = 0; p < argumentCount; p++) {
				params.put(serviceMethod.getQueryKey(p), args[p].toString());
			}

			String url = serviceMethod.url();

			String json = client.get(url, params);

			return (T) converter.convert(json);

		} catch (IOException e) {
			e.printStackTrace();

			throw new RuntimeException(e.getMessage());// 请求失败
		}
	}
}
